#define _XOPEN_SOURCE 500
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>    //close函数头文件
#include <sys/types.h> //open函数头文件
#include <sys/stat.h>  //open函数头文件
#include <fcntl.h>     //flags参数头文件
#include <elf.h>
#include <string.h>
#include <errno.h>

int main()
{

    int fd_master = open("/dev/ptmx", O_RDWR);
    if (fd_master < 0)
    {
        /* code */
        perror(strerror(errno));
        exit(errno);
    }
    if (grantpt(fd_master) != 0)
    {
        perror(strerror(errno));
        exit(errno);
    }
    if (unlockpt(fd_master) != 0)
    {
        perror(strerror(errno));
        exit(errno);
    };
    char *ttyname0 = ttyname(0);
    char *ttyname1 = ttyname(0);
    char *ttyname2 = ttyname(0);
    if (!ttyname0 || !ttyname1 || !ttyname2)
    {
        perror(strerror(errno));
        exit(errno);
    }
    printf("%s\n", ttyname0);
    printf("%s\n", ttyname1);
    printf("%s\n", ttyname2);
    printf("%s\n", ptsname(fd_master));
    // sleep(10);
    printf("sleep over\n");
    while (1)
    {
        read:
        char buf[10] = {0};
        int read_count = read(fd_master, buf, 7);
        buf[read_count] = 0;
        if (read_count < 0)
        {
            printf("%d\n", read_count);
            sleep(1);
            goto read;
        }
        printf("read content \n");
        for (int i = 0; i < read_count; i++)
        {
            printf("%d ", buf[i]);
        }
        printf("%s\n",buf);
    }
    // write:
    //     char data[8] = "master\n";
    //     int write_count = write(fd_master, data, 7);
    //     // printf("write_count %d\n", write_count);
    //     if (write_count == -1)
    //     {
    //         perror(strerror(errno));
    //         sleep(1);
    //         goto write;
    //     }
    // }
}
